#!/bin/bash

# 服务器部署脚本 - 适用于jar包和Dockerfile已在服务器上的情况
IMAGE_NAME="rocketmq-rate-limit-demo"
IMAGE_TAG="1.0.0"
CONTAINER_NAME="rocketmq-rate-limit-app"
HOST_PORT=8080
CONTAINER_PORT=8080

echo "=== 服务器部署脚本 ==="
echo ""

# 检查Docker是否运行
if ! docker info > /dev/null 2>&1; then
    echo "错误: Docker未运行，请先启动Docker服务"
    exit 1
fi

# 检查必要文件是否存在
if [ ! -f "Dockerfile" ]; then
    echo "错误: Dockerfile不存在"
    exit 1
fi

if [ ! -f "rocketmq-rate-limit-demo-1.0.0.jar" ]; then
    echo "错误: jar包不存在"
    exit 1
fi

echo "✓ 检查文件完成"
echo ""

# 检查RocketMQ网络是否存在
if ! docker network ls | grep -q "rocketmq"; then
    echo "RocketMQ网络不存在，正在创建..."
    docker network create rocketmq
    if [ $? -eq 0 ]; then
        echo "✓ RocketMQ网络创建成功"
    else
        echo "错误: 无法创建RocketMQ网络"
        exit 1
    fi
    echo ""
else
    echo "✓ RocketMQ网络已存在"
    echo ""
fi

# 停止并删除已存在的容器
echo "正在停止并删除已存在的容器..."
docker stop $CONTAINER_NAME 2>/dev/null || true
docker rm $CONTAINER_NAME 2>/dev/null || true
echo "✓ 清理旧容器完成"
echo ""

# 删除已存在的镜像
echo "正在删除已存在的镜像..."
docker rmi $IMAGE_NAME:$IMAGE_TAG 2>/dev/null || true
echo "✓ 清理旧镜像完成"
echo ""

# 构建新镜像
echo "正在构建Docker镜像..."
docker build -t $IMAGE_NAME:$IMAGE_TAG .
if [ $? -ne 0 ]; then
    echo "错误: 镜像构建失败"
    exit 1
fi
echo "✓ 镜像构建成功: $IMAGE_NAME:$IMAGE_TAG"
echo ""

# 启动容器
echo "正在启动容器..."
docker run -d \
    --name $CONTAINER_NAME \
    --network rocketmq \
    -p $HOST_PORT:$CONTAINER_PORT \
    --restart unless-stopped \
    -e SPRING_PROFILES_ACTIVE=prod \
    -e ROCKETMQ_NAMESRV_ADDR=rmqnamesrv:9876 \
    -e JAVA_OPTS="-server -Xms512m -Xmx1g -Xmn256m -XX:+UseG1GC -XX:+UseContainerSupport" \
    $IMAGE_NAME:$IMAGE_TAG

if [ $? -ne 0 ]; then
    echo "错误: 容器启动失败"
    exit 1
fi

echo "✓ 容器启动成功"
echo ""

# 等待应用启动
echo "等待应用启动..."
sleep 15

# 检查容器状态
echo "=== 容器状态 ==="
docker ps | grep $CONTAINER_NAME

echo ""
echo "=== 容器日志 ==="
docker logs --tail 30 $CONTAINER_NAME

echo ""
echo "=== 部署完成 ==="
echo "应用地址: http://localhost:$HOST_PORT"
echo "健康检查: http://localhost:$HOST_PORT/api/rocketmq/health"
echo "RocketMQ NameServer: rmqnamesrv:9876 (容器网络)"
echo ""
echo "=== 常用命令 ==="
echo "查看容器日志: docker logs -f $CONTAINER_NAME"
echo "进入容器: docker exec -it $CONTAINER_NAME /bin/bash"
echo "停止容器: docker stop $CONTAINER_NAME"
echo "重启容器: docker restart $CONTAINER_NAME"
echo "删除容器: docker rm $CONTAINER_NAME"
echo "删除镜像: docker rmi $IMAGE_NAME:$IMAGE_TAG"
echo ""
echo "=== 网络信息 ==="
echo "应用容器已加入RocketMQ网络，可通过容器名称访问RocketMQ服务"
echo "查看网络: docker network inspect rocketmq"
